package de.tsystems.jsfdict.api.impl;

import de.tsystems.jsfdict.model.Language;
import de.tsystems.jsfdict.model.Translation;
import de.tsystems.jsfdict.model.Word;

import javax.inject.Named;
import java.util.List;

@Named("transactionDao")
class TranslationDaoImpl extends AbstractDao<Translation> implements TranslationDao {
    @Override
    public Class<Translation> getEntityClass() {
        return Translation.class;
    }

    @Override
    public List<Word> getTranslationWords(Word word, Language language) {
        return (List<Word>) getCurrentSession()
                .createQuery("from Word as word " +
                    "where id in ( " +
                    "select case when lword.id=:wordId then rword.id else lword.id end " +
                    "from Translation as translation " +
                    "inner join translation.left as lword " +
                    "inner join translation.right as rword " +
                    "where (lword.id=:wordId and rword.language=:languageId) " +
                    "or (rword.id=:wordId and lword.language=:languageId)"+
                    ")")
                .setParameter("wordId", word.getId())
                .list();
    }

    @Override
    public List<Word> getTranslationWords(Word word) {
        return (List<Word>) getCurrentSession()
                .createQuery("from Word as word " +
                    "where id in ( " +
                    "select case when lword.id=:wordId then rword.id else lword.id end " +
                    "from Translation as translation " +
                    "inner join translation.left as lword " +
                    "inner join translation.right as rword " +
                    "where lword.id=:wordId or rword.id=:wordId " +
                ")")
                .setParameter("wordId", word.getId())
                .list();
    }

    @Override
    public boolean isTranslationExist(Word left, Word right) {
        return getCurrentSession()
                .createQuery("from Translation t where t.left=:left and t.right=:right")
                .setParameter("left", left).setParameter("right", right)
                .list().size() > 0;
    }

    @Override
    public Translation create(Word left, Word right) {
        Translation translation = new Translation();
        translation.setLeft(left);
        translation.setRight(right);
        return save(translation);
    }

}
